<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的订单</title>
    <link rel="stylesheet" href="../js/element-ui/lib/theme-chalk/index.css">
    <style>
        body {
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
        }
        .order-container {
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }
        .order-header {
            margin-bottom: 20px;
            font-size: 18px;
            font-weight: bold;
            color: #333;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .search-form {
            margin-bottom: 20px;
            padding: 15px;
            background-color: #f8f8f9;
            border-radius: 4px;
        }
        .search-form .el-form-item {
            margin-bottom: 0;
            margin-right: 15px;
        }
        .order-table {
            width: 100%;
            border-collapse: collapse;
        }
        .order-table th {
            background-color: #f8f8f9;
            color: #515a6e;
            font-weight: 500;
            text-align: left;
            padding: 12px 10px;
            border-bottom: 1px solid #e8eaec;
        }
        .order-table td {
            padding: 12px 10px;
            border-bottom: 1px solid #e8eaec;
            color: #606266;
        }
        .order-table tr:hover td {
            background-color: #f5f7fa;
        }
        .order-status {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 3px;
            font-size: 12px;
        }
        /* 不同订单状态的样式 */
        .status-pending_payment {
            background-color: #fff1f0;
            color: #f5222d;
        }
        .status-processing {
            background-color: #fff7e6;
            color: #fa8c16;
        }
        .status-shipped {
            background-color: #e6f7ff;
            color: #1890ff;
        }
        .status-completed {
            background-color: #f6ffed;
            color: #52c41a;
        }
        .order-amount {
            font-weight: bold;
            color: #f56c6c;
        }
        .order-date {
            color: #909399;
            white-space: nowrap;
        }
        .order-action .el-button {
            padding: 7px 10px;
        }
        .no-data {
            text-align: center;
            padding: 50px 0;
            color: #909399;
        }
        .company-name {
            max-width: 150px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        /* 移除地址的宽度限制 */
        .address {
            white-space: normal;
            word-break: break-all;
        }
        .batch-actions {
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
<div id="app">
    <div class="order-container">
        <div class="order-header">
            <span>我的订单</span>
            <div>
                <el-button type="primary" @click="resetSearch">重置查询</el-button>
                <el-button type="success" @click="exportSelectedToExcel" :disabled="selection.length === 0">导出选中订单</el-button>
            </div>
        </div>

        <div class="batch-actions" v-if="selection.length > 0">
            <el-tag type="info">已选择 {{ selection.length }} 条订单</el-tag>
            <el-button size="mini" @click="clearSelection">清空选择</el-button>
        </div>

        <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="订单编号">
                <el-input v-model="searchForm.orderNumber" placeholder="请输入订单编号" clearable></el-input>
            </el-form-item>
            <el-form-item label="商品货号">
                <el-input v-model="searchForm.productNumber" placeholder="请输入商品货号" clearable></el-input>
            </el-form-item>
            <el-form-item label="订单状态">
                <el-select v-model="searchForm.status" placeholder="请选择订单状态" clearable>
                    <el-option label="全部" value=""></el-option>
                    <el-option label="待付款" value="pending_payment"></el-option>
                    <el-option label="处理中" value="processing"></el-option>
                    <el-option label="已发货" value="shipped"></el-option>
                    <el-option label="已完成" value="completed"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="订单时间">
                <el-date-picker
                        v-model="searchForm.dateRange"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd">
                </el-date-picker>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-form-item>
        </el-form>

        <el-table
                :data="filteredOrderList"
                style="width: 100%"
                v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(255, 255, 255, 0.8)"
                @selection-change="handleSelectionChange"
                ref="orderTable">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="userId" label="客户号" width="120"></el-table-column>
            <el-table-column label="订单编号" width="180">
                <template slot-scope="scope">
                    <el-link type="primary" @click="viewOrderDetail(scope.row.orderNumber)">
                        {{ scope.row.orderNumber }}
                    </el-link>
                </template>
            </el-table-column>
            <el-table-column prop="companyName" label="公司名称" width="180">
                <template slot-scope="scope">
                    <div class="company-name" :title="scope.row.companyName">{{ scope.row.companyName }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="180"></el-table-column>
            <el-table-column prop="status" label="订单状态" width="120">
                <template slot-scope="scope">
                    <span class="order-status" :class="'status-' + scope.row.status">
                        {{ formatStatus(scope.row.status) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="shippingInfo" label="物流信息" width="180">
                <template slot-scope="scope">
                    {{ formatShippingInfo(scope.row) }}
                </template>
            </el-table-column>
            <el-table-column prop="detailAddress" label="地址">
                <template slot-scope="scope">
                    <div class="address">
                        {{ formatFullAddress(scope.row) }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="totalAmount" label="订单总金额" width="120" align="right">
                <template slot-scope="scope">
                    <span class="order-amount">¥{{ formatAmount(scope.row.totalAmount) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="订单日期" width="180" sortable>
                <template slot-scope="scope">
                    <span class="order-date">{{ formatDate(scope.row.createdAt) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="120" class="order-action">
                <template slot-scope="scope">
                    <el-button type="primary" @click="initReorderDialog(scope.row)" size="medium">再次下单</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="block" style="text-align: center;padding: 20px;">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[3,5,7,10]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalCount">
            </el-pagination>
        </div>

        <div class="no-data" v-if="filteredOrderList.length === 0 && !loading">
            <i class="el-icon-box" style="font-size: 50px; color: #c0c4cc;"></i>
            <p>暂无订单数据</p>
        </div>

        <!-- 再次下单对话框 -->
        <el-dialog
                title="再次下单"
                :visible.sync="reorderDialogVisible"
                width="70%"
                top="5vh">

            <el-form :model="reorderForm" label-width="120px">
                <!-- 订单基本信息 -->
                <el-form-item label="订单编号">
                    <el-input v-model="reorderForm.orderNumber" disabled></el-input>
                </el-form-item>

                <el-form-item label="原订单状态">
                    <el-input :value="formatStatus(reorderForm.originalStatus)" disabled></el-input>
                </el-form-item>

                <el-form-item label="收货地址" prop="shippingAddressId">
                    <el-select
                            v-model="reorderForm.shippingAddressId"
                            placeholder="请选择收货地址"
                            style="width: 100%">
                        <el-option
                                v-for="address in userAddresses"
                                :key="address.addressId"
                                :label="formatAddressLabel(address)"
                                :value="address.addressId">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="配送方式">
                    <el-radio-group v-model="reorderForm.shippingMethod">
                        <el-radio label="delivery">快递配送</el-radio>
                        <el-radio label="self_pickup">门店自提</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="订单备注">
                    <el-input
                            type="textarea"
                            v-model="reorderForm.remark"
                            placeholder="请输入订单备注"></el-input>
                </el-form-item>

                <!-- 商品列表 -->
                <el-form-item label="商品清单">
                    <el-table :data="reorderItems" border style="width: 100%">
                        <el-table-column prop="productName" label="商品名称" width="250"></el-table-column>
                        <el-table-column prop="productNumber" label="商品货号" width="150"></el-table-column>
                        <el-table-column label="数量" width="150" align="center">
                            <template slot-scope="scope">
                                <el-input-number
                                        v-model="scope.row.quantity"
                                        :min="1"
                                        size="mini"></el-input-number>
                            </template>
                        </el-table-column>
                        <el-table-column label="单价" width="120" align="right">
                            <template slot-scope="scope">
                                ¥{{ formatAmount(scope.row.unitPrice) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="小计" width="120" align="right">
                            <template slot-scope="scope">
                                ¥{{ formatAmount(scope.row.unitPrice * scope.row.quantity) }}
                            </template>
                        </el-table-column>
                    </el-table>

                    <div style="text-align: right; margin-top: 20px;">
                        <div style="font-size: 14px; color: #606266; margin-bottom: 5px;">
                            共 {{ totalReorderQuantity }} 件商品
                        </div>
                        <div style="font-size: 16px;">
                            合计：<span class="total-amount">¥{{ formatAmount(reorderTotalAmount) }}</span>
                        </div>
                    </div>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
        <el-button @click="reorderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReorder">确认下单</el-button>
    </span>
        </el-dialog>

    </div>

</div>

<script src="../js/vue.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script src="../js/element-ui/lib/index.js"></script>
<!-- 引入xlsx库用于导出Excel -->
<script src="../js/xlsx.full.min.js"></script>
<script>
    // 创建并配置axios实例
    const api = axios.create({
        baseURL: '/',
        timeout: 10000,
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        }
    });

    // 响应拦截器
    api.interceptors.response.use(
        response => {
            const res = response.data;
            if (res.code === 20041 || res.code === 20011) {
                return res;
            } else {
                return Promise.reject(new Error(res.msg || '请求失败'));
            }
        },
        error => {
            console.error('请求出错:', error);
            return Promise.reject(error);
        }
    );

    new Vue({
        el: '#app',
        data() {
            return {
                orderList: [],
                filteredOrderList: [],
                loading: true,
                searchForm: {
                    orderNumber: '',
                    productNumber: '', // 新增商品货号字段
                    status: '',
                    dateRange: []
                },

                selection: [],// 存储选中的订单
                currentPage: 1, // 当前页码
                pageSize: 10,   // 每页显示数量
                totalCount: 0,   // 总记录数

                reorderDialogVisible: false,
                reorderForm: {
                    orderId: null,
                    orderNumber: '',
                    originalStatus: '',
                    shippingAddressId: null,
                    shippingMethod: 'delivery',
                    remark: '',
                    totalAmount: 0
                },
                reorderItems: [],
                userAddresses: []

            }
        },
        computed: {
            // ...原有计算属性...
            totalReorderQuantity() {
                return this.reorderItems.reduce((total, item) => total + item.quantity, 0);
            },
            reorderTotalAmount() {
                return this.reorderItems.reduce((total, item) => total + (item.unitPrice * item.quantity), 0);
            }
        },
        created() {
            this.fetchOrderList();
        },
        methods: {
            viewOrderDetail(orderNumber) {
                // 改为通过postMessage与父页面通信
                window.parent.postMessage({
                    type: 'changePage',
                    url: 'orderdetail.html',
                    params: { orderNumber: orderNumber }
                }, '*');
            },
            formatFullAddress(row) {
                const { province, city, district, detailAddress } = row;
                let fullAddress = [];

                // 添加省（直辖市不重复显示）
                if (province && (!city || city !== province)) {
                    fullAddress.push(province);
                }

                // 添加市（跳过 "市辖区"）
                if (city && city !== "市辖区") {
                    fullAddress.push(city);
                }

                // 添加区县
                if (district) {
                    fullAddress.push(district);
                }

                // 添加详细地址
                if (detailAddress) {
                    fullAddress.push(detailAddress);
                }

                return fullAddress.join("") || "无地址信息";
            },
            formatShippingInfo(row) {
                if (row.shippingMethod === 'delivery') {
                    return row.trackingNumber ? `物流单号: ${row.trackingNumber}` : '暂无物流信息';
                } else if (row.shippingMethod === 'self_pickup') {
                    return row.pickupCode ? `自提码: ${row.pickupCode}` : '暂无自提码';
                }
                return '未知配送方式';
            },
            async fetchOrderList() {
                this.loading = true;
                try {
                    const params = {
                        orderNumber: this.searchForm.orderNumber || undefined,
                        status: this.searchForm.status || undefined,
                        productNumber: this.searchForm.productNumber || undefined, // 新增商品货号参数
                        pageNum: this.currentPage,
                        pageSize: this.pageSize
                    };

                    if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
                        params.startDate = this.searchForm.dateRange[0];
                        params.endDate = this.searchForm.dateRange[1];
                    } else {
                        delete params.startDate;
                        delete params.endDate;
                    }

                    const res = await api.get('/user/getOrderList', { params });
                    this.filteredOrderList = res.data.list || [];
                    this.totalCount = res.data.total || 0;
                } catch (error) {
                    console.error('获取订单列表出错:', error);
                    this.$message.error(error.message || '获取订单列表失败');
                } finally {
                    this.loading = false;
                }
            },
            // 每页条数改变
            handleSizeChange(val) {
                console.log("pageSize changed to:", val); // 调试日志
                this.pageSize = val;
                this.currentPage = 1;
                this.fetchOrderList();
            },
            // 当前页改变
            handleCurrentChange(val) {
                this.currentPage = val;
                this.fetchOrderList();
            },
            handleSearch() {
                this.currentPage = 1; // 搜索时重置为第一页
                this.fetchOrderList();
            },
            resetSearch() {
                this.searchForm = {
                    orderNumber: '',
                    productNumber: '', // 重置商品货号字段
                    status: '',
                    dateRange: []
                };
                this.currentPage = 1;
                this.fetchOrderList();
                this.clearSelection();
            },
            async handleReorder(row) {
                try {
                    const response = await api.post('/order/reorder', {
                        orderId: row.orderId,  // 修正为orderId
                        userId: row.userId
                    });

                    this.$message({
                        message: response.msg || `订单 ${row.orderId} 再次下单成功`,
                        type: 'success'
                    });
                } catch (error) {
                    this.$message.error(error.message || '再次下单失败');
                }
            },
            formatAmount(amount) {
                if (amount === null || amount === undefined) return '0.00';
                return parseFloat(amount).toFixed(2);
            },
            formatDate(dateStr) {
                if (!dateStr) return '';

                // 处理数据库返回的日期格式
                const date = new Date(dateStr);

                // 格式化为本地时间字符串
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                    hour12: false
                }).replace(/\//g, '-');
            },
            formatStatus(status) {
                const statusMap = {
                    pending_payment: '待付款',
                    processing: '处理中',
                    shipped: '已发货',
                    completed: '已完成'
                };
                return statusMap[status] || status;
            },
            // 处理选中行变化
            handleSelectionChange(val) {
                this.selection = val;
            },
            // 清空选择
            clearSelection() {
                this.$refs.orderTable.clearSelection();
            },
            // 导出选中订单到Excel
            exportSelectedToExcel() {
                if (this.selection.length === 0) {
                    this.$message.warning('请至少选择一条订单');
                    return;
                }

                // 准备导出的数据
                const exportData = this.selection.map(item => {
                    return {
                        '客户号': item.userId,
                        '订单编号': item.orderNumber,
                        '公司名称': item.companyName,
                        '备注': item.remark,
                        '订单状态': this.formatStatus(item.status),
                        '地址': item.detailAddress,
                        '订单总金额': '¥' + this.formatAmount(item.totalAmount),
                        '订单日期': this.formatDate(item.createdAt)
                    };
                });

                // 创建工作簿
                const wb = XLSX.utils.book_new();
                const ws = XLSX.utils.json_to_sheet(exportData);

                // 设置列宽
                const wscols = [
                    {wch: 10}, // 客户号
                    {wch: 20}, // 订单编号
                    {wch: 20}, // 公司名称
                    {wch: 20}, // 备注
                    {wch: 10}, // 订单状态
                    {wch: 30}, // 地址
                    {wch: 15}, // 订单总金额
                    {wch: 20}  // 订单日期
                ];
                ws['!cols'] = wscols;

                // 添加工作表到工作簿
                XLSX.utils.book_append_sheet(wb, ws, "订单数据");

                // 生成Excel文件并下载
                const fileName = `订单数据_${new Date().toLocaleDateString()}.xlsx`;
                XLSX.writeFile(wb, fileName);

                this.$message.success('导出成功');
            },

            // 初始化再次下单对话框
            async initReorderDialog(row) {
                try {
                    this.loading = true;

                    // 获取当前订单信息
                    const orderRes = await api.get('/user/getOrderDetail', {
                        params: { orderNumber: row.orderNumber }
                    });

                    // 获取订单商品
                    const itemsRes = await api.get('/user/getOrderItems', {
                        params: { orderNumber: row.orderNumber }
                    });

                    // 获取用户地址
                    const addressRes = await api.get('/user/getUserAddress');

                    // 填充表单数据
                    this.reorderForm = {
                        orderId: orderRes.data.orderId,
                        orderNumber: row.orderNumber,
                        originalStatus: row.status,
                        shippingAddressId: null,
                        shippingMethod: row.shippingMethod,
                        remark: '',
                        totalAmount: 0
                    };

                    // 填充商品数据
                    this.reorderItems = itemsRes.data.map(item => ({
                        ...item,
                        quantity: item.quantity // 初始数量与原订单相同
                    }));

                    // 填充地址数据
                    this.userAddresses = addressRes.data;

                    // 如果有默认地址，自动选中
                    const defaultAddress = this.userAddresses.find(addr => addr.isDefault === 1);
                    if (defaultAddress) {
                        this.reorderForm.shippingAddressId = defaultAddress.addressId;
                    }

                    this.reorderDialogVisible = true;
                } catch (error) {
                    console.error('初始化再次下单失败:', error);
                    this.$message.error('初始化再次下单失败: ' + (error.response?.data?.msg || error.message));
                } finally {
                    this.loading = false;
                }
            },

            // 格式化地址显示
            formatAddressLabel(address) {
                return `${address.receiverName} ${address.phone} ${address.province}${address.city}${address.district}${address.detailAddress}`;
            },

            // 提交再次下单
            async submitReorder() {
                try {
                    // 验证表单
                    if (!this.reorderForm.shippingAddressId && this.reorderForm.shippingMethod === 'delivery') {
                        this.$message.warning('请选择收货地址');
                        return;
                    }

                    // 2. 获取当前用户的 userId（关键修改点）
                    const userIdResponse = await axios.get('/user/api/current-user-id');
                    const userId = userIdResponse.data;

                    // 准备订单数据
                    const orderData = {
                        userId: userId,
                        remark: this.reorderForm.remark,
                        status: 'processing', // 新订单状态设置为processing
                        shippingAddressId: this.reorderForm.shippingMethod === 'delivery'
                            ? this.reorderForm.shippingAddressId
                            : null,
                        shippingMethod: this.reorderForm.shippingMethod,
                        totalAmount: this.reorderTotalAmount,
                        // 订单编号由后端自动生成
                    };

                    // 准备商品数据
                    const itemsData = this.reorderItems.map(item => ({
                        productId: item.productId,
                        quantity: item.quantity,
                        unitPrice: item.unitPrice
                    }));

                    // 提交订单
                    const res = await api.post('/user/insertOrder', {
                        ...orderData,
                        items: itemsData
                    });

                    this.$message.success('下单成功');
                    this.reorderDialogVisible = false;

                    // 刷新订单列表
                    this.fetchOrderList();
                } catch (error) {
                    console.error('下单失败:', error);
                    this.$message.error('下单失败: ' + (error.response?.data?.msg || error.message));
                }
            }

        },
    });
</script>
</body>
</html>